<?php

class Car extends Auto_Db_Simple
{
    protected $_name = 'cars';

    public function getList($filter = array())
    {
        $db = $this->getAdapter();

        $select = $db->select()
            ->from(array('c' => 'cars'))
            ->join(array('m' => 'makes'), 'c.make_id = m.id', array('make_name' => 'm.name'));

        if (isset($filter['make_id'])) {
            $select->where('c.make_id = ?', $filter['make_id']);
        }
        if (isset($filter['year_from'])) {
            $select->where('c.produced >= ?', $filter['year_from']);
        }
        if (isset($filter['year_to'])) {
            $select->where('c.produced <= ?', $filter['year_to']);
        }
        if (isset($filter['keyword'])) {
            $select->where('model LIKE ?', '%' . $filter['keyword'] . '%');
        }

        $select->order('make_name')->order('model');

        $stmt = $db->query($select);
        return $stmt->fetchAll();
    }

    public function get($id)
    {
        $out['car'] = $this->find($id)->current();

        $db = $this->getAdapter();

        $select = $db->select()
            ->from('cars_features')
            ->where($db->quoteInto('car_id=?', $id));
        $stmt = $db->query($select);

        $features = array();
        while (false !== ($row = $stmt->fetch())) {
            $features[] = $row['feature_id'];
        }

        $out['features'] = $features;

        return $out;
    }

    public function save($params, $id = null)
    {
        $features = $params['features'];
        unset($params['features']);
        unset($params['save']);

        if (empty($params['price'])) {
            $params['price'] = 0;
        }
        if (empty($params['kms'])) {
            $params['kms'] = 0;
        }

        $db = $this->getAdapter();

        $db->beginTransaction();

        try {

            if (isset($id)) { // update
                $this->update($params, $db->quoteInto('id=?', $id));
            } else { // insert
                $id = $this->insert($params);
            }

            // save features
            $db->delete('cars_features', $db->quoteInto('car_id=?', $id));
            foreach ($features as $fid) {
                $db->insert('cars_features', array('car_id' => $id, 'feature_id' => $fid));
            }

            $db->commit();

        } catch (Zend_Db_Exception $e) {
            $db->rollBack();
        }
    }

    public function remove($id)
    {
        $db = $this->getAdapter();
        $db->delete('cars_features', $db->quoteInto('car_id=?', $id));

        parent::remove($id);
    }
}
